package com.qf.ucenter.controller;

import com.qf.business.extentions.UserInfoUtil;
import com.qf.trade.feign.ITradeFeign;
import com.qf.ucenter.entity.Resp;
import com.qf.ucenter.entity.User;
import com.qf.ucenter.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Random;

/**
 * 用户业务处理接口
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ITradeFeign tradeFeign;

    @Autowired
    private IUserService userService;

    /**
     * 用户注册
     *
     * @param userName
     * @return success:成功
     */
    @GetMapping("register/{userName}")
    public Resp register(@PathVariable String userName) {
        UserInfoUtil.getUserInfo();

        Resp result = new Resp();

        //todo 新增用户
        Long userId = new Random().nextLong();
        System.out.println(String.format("新增用户 userName:%s userId:%d", userName, userId));
        //todo 调用钱包初始化接口
        String url = "http://trade/wallet/init/" + userId;
        String resp = restTemplate.getForObject(url, String.class);
        System.out.println(String.format("调用钱包接口 resp:%s", resp));

        result.setData(resp);
        return result;
    }

    @GetMapping("registerByFeign/{userName}")
    public Resp registerByFeign(@PathVariable String userName) {
        Resp result = new Resp();
        //todo 新增用户
        Long userId = new Random().nextLong();
        System.out.println(String.format("新增用户 userName:%s userId:%d", userName, userId));
        //todo 调用钱包初始化接口
        String resp = tradeFeign.init(userId);
        //todo 送20元商品，扣减钱包余额
        System.out.println(String.format("调用钱包接口 resp:%s", resp));
        result.setData(resp);
        return result;
    }

    @PostMapping("login")
    public Resp login(User user) {
        Resp result = new Resp();
        User respUser = userService.login(user);
        result.setData(respUser);
        return result;
    }
}
